<?php

namespace app\models;

use Yii;
use yii\data\Pagination;

/**
 * This is the model class for table "{{%project}}".
 *
 * @property int $id 项目id
 * @property string $name 名称
 * @property string $desc 描述
 * @property int $created_uid 创建者uid
 * @property int $created_time 创建时间
 * @property int $is_public 是否公开
 * @property int $sort 序号
 * @property int $is_del 是否删除 0正常 , 1删除
 */
class Project extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%project}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['created_uid', 'created_time', 'is_public', 'sort', 'is_del'], 'integer'],
            [['name', 'desc'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'desc' => 'Desc',
            'created_uid' => 'Created Uid',
            'created_time' => 'Created Time',
            'is_public' => 'Is Public',
            'sort' => 'Sort',
            'is_del' => 'Is Del',
        ];
    }

    /**
     * 获取所有的项目
     * @param array $map
     * @param string $order
     * @return array
     */
    public static function getAllProjects($map = [],$order = "created_time desc",$page = true)
    {
        $query = static::find();
        if(isset($map['title'])){
            $query->andFilterWhere(['like','name',$map['name']]);
        }

        if (isset($map['created_uid'])){
            $query->andFilterWhere(['or',['created_uid' => $map['created_uid']],['is_del' => $map['is_del'], 'is_public' => $map['is_public']]]);
        } else {
            $query->andFilterWhere(['is_del' => $map['is_del'],'is_public' => $map['is_public']]);
        }
        if ($page){
            $pageSize = isset($map['pageSize']) ? $map['pageSize'] : 10;
            $countQuery = clone $query;
            $pages = new Pagination([
                'pageSize' => $pageSize,
                'totalCount' => $countQuery->count(),
                'defaultPageSize' => $pageSize
            ]);

            $query->orderBy($order);
            $items = $query->offset($pages->offset)
                ->limit($pages->limit)
                ->asArray()
                ->all();
        } else {
            $items = $query->asArray()->all();
        }


        return compact('items','pages');
    }
}
